package com.example.action;

import com.example.bean.Cart;
import com.example.bean.CartItem;
import com.example.bean.Product;
import com.example.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addCart")
public class AddCartServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pid = Integer.parseInt(request.getParameter("pid"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        ProductService service = new ProductService();
        Product product = service.selectProductInfoById(pid);
        CartItem item = new CartItem();
        item.setProduct(product);
        item.setCount(quantity);
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null){
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }
        cart.addProdToCart(item);
        request.setAttribute("box", cart);
        request.getRequestDispatcher("shop-cart.jsp").forward(request,response);
    }
}
